package com.liushuai.gateway.customize;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;


/**
 * @author ：liushuai
 * @date ：Created in 2022/8/8 10:06
 * @description：
 * @modified By：
 * @version: $
 */
//@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomGatewayFilterFactory.Config> {
    /**
     * Filter key.
     */
    public static final String FILTER_KEY = "filterKey";

    /**
     * Filter key.
     */
    public static final String FILTER_VAL = "filterVal";
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    public CustomGatewayFilterFactory() {
        super(CustomGatewayFilterFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(FILTER_KEY, FILTER_VAL);
    }

    @Override
    public GatewayFilter apply(CustomGatewayFilterFactory.Config config) {
        /**
         * 可以是用lamda表达式，也可以new GatewayFilter() {}
         */
        return (exchange, chain) -> {
            log.info("========> 进入自定义过滤器 key：{} val：{}", config.getFilterKey(), config.getFilterVal());

            ServerHttpRequest request = exchange.getRequest();
            log.info("========> 请求内容 url：{} method：{} param:{} headers：{}",
                    request.getURI(), request.getMethodValue(), request.getQueryParams(), request.getHeaders());
            return chain.filter(exchange);
        };
    }

    public static class Config {

        private String filterKey;

        private String filterVal;

        public String getFilterKey() {
            return filterKey;
        }

        public void setFilterKey(String filterKey) {
            this.filterKey = filterKey;
        }

        public String getFilterVal() {
            return filterVal;
        }

        public void setFilterVal(String filterVal) {
            this.filterVal = filterVal;
        }
    }
}
